package com.itheima.ydd.controller;


import com.itheima.ydd.common.R;
import com.itheima.ydd.pojo.FilePath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件上传下载
 */
@Slf4j
@Controller
@RequestMapping("common")
public class CommonController {
    @Value("${ydd.path}")
    private String basePath;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("upload")
    public ResponseEntity<R<FilePath>> upload(MultipartFile file, String type){
        //设定时间格式
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取右边图片文件类型
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //获取当前时间毫秒值，并组合成新文件名
        String fileName = date.getTime() + suffix;
        //获取存储路径
        String savePath = "undefinedupload/" + type + "/" + simpleDateFormat.format(date.getTime()) + "/" + fileName;


        //封装Filepath对象
        FilePath filePath=new FilePath();
        filePath.setSavePath(savePath);
        filePath.setName(file.getOriginalFilename());
        //filePath.setMime("image/png");
        log.info(basePath+fileName);

        //判断文件上传类型
        if (type.equals("images")) {
            filePath.setMime("image/" + suffix);
        }
        //创建一个目录对象
        File dir = new File(basePath +savePath);
        //创建一个测试目录对象
        //File dirtest = new File(path);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在，重新创建
            dir.mkdirs();

        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + savePath));

        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok(R.success(filePath));
    }



}
